package shuanfa;

import java.util.HashMap;
import java.util.List;

public class ReverseList {
    static class ListNode{
        int val;
        ListNode next;
        public ListNode(int val,ListNode next){
            this.val = val;
            this.next = next;
        }
    }
    //迭代
    public static ListNode reverseList(ListNode head){
        ListNode pre = null;
        ListNode next;
        ListNode cur = head;
        while (cur!=null){
            next = cur.next;//保存当前节点的下一个节点
            cur.next = pre;//当前节点的下一个节点指向前前一个节点
            pre = cur;//pre后移
            cur = next;//当前节点后移
        }
        return pre;
    }
    //递归
    public static ListNode recursion(ListNode head){
        if (head == null || head.next == null){
            return head;
        }
        ListNode newHead = recursion(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public static void iterate(ListNode head){
        ListNode cur = head;
        while (cur !=null){
            System.out.println(cur.val);
            cur = cur.next;
        }
    }
    public static void main(String[] args) {
        ListNode node5 = new ListNode(5, null);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode head = new ListNode(1, node2);
        //ListNode reverseList = reverseList(head);
        ListNode listNode = recursion(head);
        new HashMap<>();
        iterate(listNode);
    }
}
